// controllers/comboController.js
const pool = require('../config/db');
const { sendResponse } = require('../utils/response');

// 获取所有套餐
const getAllCombos = async (req, res) => {
  try {
    const [rows] = await pool.execute('SELECT * FROM combos WHERE status = 1');
    sendResponse(res, 200, '获取套餐成功', rows);
  } catch (error) {
    sendResponse(res, 500, '获取套餐失败', error.message);
  }
};

// 获取单个套餐
const getComboById = async (req, res) => {
  const { id } = req.params;
  try {
    const [rows] = await pool.execute('SELECT * FROM combos WHERE id = ? AND status = 1', [id]);
    if (rows.length === 0) {
      return sendResponse(res, 404, '套餐未找到');
    }
    sendResponse(res, 200, '获取套餐成功', rows[0]);
  } catch (error) {
    sendResponse(res, 500, '获取套餐失败', error.message);
  }
};

// 创建套餐（需要管理员权限）
const createCombo = async (req, res) => {
  const { name, price, original_price, image_url, description, is_adjustable } = req.body;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const [result] = await connection.execute(
      'INSERT INTO combos (name, price, original_price, image_url, description, is_adjustable) VALUES (?, ?, ?, ?, ?, ?)',
      [name, price, original_price, image_url, description, is_adjustable || 0]
    );
    const comboId = result.insertId;
    await connection.commit();
    sendResponse(res, 201, '创建套餐成功', { id: comboId });
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '创建套餐失败', error.message);
  } finally {
    connection.release();
  }
};

// 更新套餐（需要管理员权限）
const updateCombo = async (req, res) => {
  const { id } = req.params;
  const { name, price, original_price, image_url, description, is_adjustable } = req.body;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const [result] = await connection.execute(
      'UPDATE combos SET name = ?, price = ?, original_price = ?, image_url = ?, description = ?, is_adjustable = ? WHERE id = ?',
      [name, price, original_price, image_url, description, is_adjustable, id]
    );
    if (result.affectedRows === 0) {
      return sendResponse(res, 404, '套餐未找到');
    }
    await connection.commit();
    sendResponse(res, 200, '更新套餐成功');
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '更新套餐失败', error.message);
  } finally {
    connection.release();
  }
};

// 删除套餐（需要管理员权限，逻辑删除）
const deleteCombo = async (req, res) => {
  const { id } = req.params;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    const [result] = await connection.execute('UPDATE combos SET status = 0 WHERE id = ?', [id]);
    if (result.affectedRows === 0) {
      return sendResponse(res, 404, '套餐未找到');
    }
    await connection.commit();
    sendResponse(res, 200, '删除套餐成功');
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '删除套餐失败', error.message);
  } finally {
    connection.release();
  }
};

// 获取套餐包含的菜品
const getComboItems = async (req, res) => {
  const { id } = req.params;
  try {
    const [rows] = await pool.execute(
      `SELECT ci.*, d.name as dish_name, d.price as dish_price, d.image_url as dish_image
       FROM combo_items ci
       LEFT JOIN dishes d ON ci.dish_id = d.id
       WHERE ci.combo_id = ?`,
      [id]
    );
    sendResponse(res, 200, '获取套餐项目成功', rows);
  } catch (error) {
    sendResponse(res, 500, '获取套餐项目失败', error.message);
  }
};

// 添加套餐菜品
const addComboItem = async (req, res) => {
  const { id } = req.params;
  const { dish_id, quantity, is_optional, alternative_ids } = req.body;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    // 检查套餐是否存在
    const [combos] = await connection.execute('SELECT * FROM combos WHERE id = ?', [id]);
    if (combos.length === 0) {
      await connection.rollback();
      return sendResponse(res, 404, '套餐未找到');
    }
    // 检查菜品是否存在
    const [dishes] = await connection.execute('SELECT * FROM dishes WHERE id = ?', [dish_id]);
    if (dishes.length === 0) {
      await connection.rollback();
      return sendResponse(res, 404, '菜品未找到');
    }
    const [result] = await connection.execute(
      `INSERT INTO combo_items (combo_id, dish_id, quantity, is_optional, alternative_ids)
       VALUES (?, ?, ?, ?, ?)`,
      [id, dish_id, quantity || 1, is_optional || 0, alternative_ids || null]
    );
    await connection.commit();
    sendResponse(res, 201, '添加套餐项目成功', { id: result.insertId });
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '添加套餐项目失败', error.message);
  } finally {
    connection.release();
  }
};

// 更新套餐菜品
const updateComboItem = async (req, res) => {
  const { id, item_id } = req.params;
  const { dish_id, quantity, is_optional, alternative_ids } = req.body;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    // 检查套餐项目是否存在且属于该套餐
    const [items] = await connection.execute(
      'SELECT * FROM combo_items WHERE id = ? AND combo_id = ?',
      [item_id, id]
    );
    if (items.length === 0) {
      await connection.rollback();
      return sendResponse(res, 404, '套餐项目未找到');
    }
    // 检查菜品是否存在
    if (dish_id) {
      const [dishes] = await connection.execute('SELECT * FROM dishes WHERE id = ?', [dish_id]);
      if (dishes.length === 0) {
        await connection.rollback();
        return sendResponse(res, 404, '菜品未找到');
      }
    }
    const [result] = await connection.execute(
      `UPDATE combo_items SET dish_id = ?, quantity = ?, is_optional = ?, alternative_ids = ?
       WHERE id = ? AND combo_id = ?`,
      [dish_id, quantity, is_optional, alternative_ids, item_id, id]
    );
    await connection.commit();
    sendResponse(res, 200, '更新套餐项目成功');
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '更新套餐项目失败', error.message);
  } finally {
    connection.release();
  }
};

// 删除套餐菜品
const deleteComboItem = async (req, res) => {
  const { id, item_id } = req.params;
  const connection = await pool.getConnection();
  try {
    await connection.beginTransaction();
    // 检查套餐项目是否存在且属于该套餐
    const [items] = await connection.execute(
      'SELECT * FROM combo_items WHERE id = ? AND combo_id = ?',
      [item_id, id]
    );
    if (items.length === 0) {
      await connection.rollback();
      return sendResponse(res, 404, '套餐项目未找到');
    }
    const [result] = await connection.execute(
      'DELETE FROM combo_items WHERE id = ? AND combo_id = ?',
      [item_id, id]
    );
    await connection.commit();
    sendResponse(res, 200, '删除套餐项目成功');
  } catch (error) {
    await connection.rollback();
    sendResponse(res, 500, '删除套餐项目失败', error.message);
  } finally {
    connection.release();
  }
};

module.exports = {
  getAllCombos,
  getComboById,
  createCombo,
  updateCombo,
  deleteCombo,
  getComboItems,
  addComboItem,
  updateComboItem,
  deleteComboItem
};